package vboot.web.init;

import org.springframework.context.annotation.PropertySource;
import vboot.core.module.ass.oss.config.AssOssConfigService;
import vboot.core.module.sys.org.user.SysOrgUserRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

//数据库初始化监听器
@Configuration
@Slf4j
@PropertySource(value = { "classpath:config/app-init.properties" },encoding = "UTF-8")
public class DbInitListener implements ApplicationListener<ContextRefreshedEvent> {

    @Value("${app.init.orgType}")
    private String ORG_TYPE;

    @Value("${app.init.orgName}")
    private String ORG_NAME;

    @Value("${app.init.orgRootId}")
    private String ORG_ROOT_ID;

    @Value("${app.init.uiType}")
    private String UI_TYPE;


    //首次启动，数据库生成后，初始化组织架构，菜单，权限角色,接口等信息
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        try {
            if (!userDao.existsById("sa")) {
                System.out.println("首次启动系统，正在进行数据库初始化，请耐心等待。");
                sysOrgInit.initRoot(ORG_NAME,ORG_ROOT_ID);
                sysOrgInit.initSa();
                if ("test".equals(ORG_TYPE)) {
                    sysOrgInit.initTestOrg();
                }
                if ("wc".equals(ORG_TYPE)) {
                    sysOrgInit.initTestOrg();
                    sysOrgInit.initWcDept();
                }
                System.out.println("1 初始化组织架构完毕");
//                sysOrgInit.initPost();
//                sysOrgInit.initGroup();

                if ("vben".equals(UI_TYPE)) {
                    sysPortalVbenInit.initPortal();
                    sysPortalVbenInit.initSysMenu();
                    sysPortalVbenInit.initSaMenu();
                }else{
                    sysPortalVueInit.initPortal();
                    sysPortalVueInit.initSysMenu();
                    sysPortalVueInit.initSaMenu();
                }

                System.out.println("2 初始化门户菜单完毕");
                assInit.initData();
                System.out.println("3 初始化辅助数据完毕");
            }
            sysApiInit.initApi();
            assOssConfigService.init();

        } catch (Exception e) {
            System.err.println("初始化出错");
            e.printStackTrace();
        }
    }

    @Autowired
    private SysOrgUserRepo userDao;

    @Autowired
    private AssOssConfigService assOssConfigService;

    @Autowired
    private SysOrgInit sysOrgInit;

    @Autowired
    private AssInit assInit;

    @Autowired
    private SysApiInit sysApiInit;

    @Autowired
    private SysPortalVbenInit sysPortalVbenInit;

    @Autowired
    private SysPortalVueInit sysPortalVueInit;

}